//路由的配置文件
//从 vue-router 插件包引入createRouter的方法
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { App } from "vue";
import LoginView from "../views/login/LoginView.vue";
//  import MainView from "../views/login/MainView.vue";
import MainView from "../views/main/MainView.vue";
import HomeView from "../views/home/HomeView.vue";
import NotFound from "../views/404/NotFound.vue";
import UsersView from "../views/users/list/UsersView.vue";
import UsersGroup from "../views/users/group/UsersGroup.vue";
import SetupDelivery from "../views/setup/delivery/SetupDelivery.vue";

import Productsadd from "../views/products/add/Productsadd.vue";

import Homesorder from "../views/homes/order/Homesorder.vue";
import Productslist from "@/views/products/list/Productslist.vue";
import ProductsHandle from "@/views/products/list/ProductsHandle.vue";
import SetupPermis from "@/views/setup/permission/SetupPermis.vue";
import Permission2Menusd from "@/views/setup/permission2/menusd/Permission2Menusd.vue";
import PermissionAdmins from "@/views/setup/permission2/admins/PermissionAdmins.vue";
import PermissionRoles from "@/views/setup/permission2/roles/PermissionRoles.vue";
import PermissionSet from "@/views/setup/permission2/settings/PermissionSet.vue";
import { useAdminStore } from '@/store/admin';
import { permission } from "process";
import MenuItem from "element-plus/es/components/menu/src/utils/menu-item.mjs";
const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        component: LoginView,
         name: 'Login',

    },

    {
        path: '/',
        component: MainView,
         name: 'MainView',


        // children: [
        //     {
        //         path: 'home',
        //         component: HomeView
        //     },

        //     {
        //         path: 'users/list',
        //         component: UsersView,  //用户管理
        //     },

        //     {
        //         path: 'users/group',
        //         component: UsersGroup,  //用户分组
        //     },

        //     {
        //         path: '/setup/delivery',
        //         component: SetupDelivery,//设置-配送员管理
        //     },

        //     {
        //         path: '/setup/permission',
        //         component: SetupPermis,//权限设置1
        //     },
        //     {
        //         path: '/setup/permission2/menusd',
        //         component: Permission2Menusd,//权限设置2
        //     },
        //     {
        //         path: '/setup/permission2/admins',
        //         component: PermissionAdmins,//角色管理
        //     },
        //     {
        //         path: '/setup/permission2/roles',//管理员列表
        //         component: PermissionRoles,
        //     },
        //     {
        //         path: '/setup/permission2/settings',//角色管理2
        //         component: PermissionSet,
        //     },
        //     {
        //         path: '/products/add',
        //         component: Productsadd,//商品分类
        //     },
        //     {
        //         path: '/products/list',
        //         component: Productslist,//商品管理
        //     },
        //     {
        //         path: '/homes/order',
        //         component: Homesorder,//收银订单
        //     },
        //     {
        //         path: 'products/adds',
        //         component: ProductsHandle,
        //     },
        //     {
        //         path: 'products/update/:_id?',
        //         component: ProductsHandle
        //     },

        // ],



    },
    // //和前面所有路由都匹配不上时，匹配404路由
    {
        path: '/:pathMatch(.*)*',
        component: NotFound,
    },

]


//RouteRecordRaw类型名称，ctrl加鼠标左键单击RouteRecordRaw 可以打开一个文件
const router = createRouter({
    //routes:用来进行项目中所有页面的路由配置
    routes,
    // history是配置路由模式
    history: createWebHistory()

});



//路由白名单（不用登录可以直接访问的页面）
const WHITE_LIST = ['/login'];

let isAdded = false;






//全局前置守卫
router.beforeEach(async (to, from) => {
    if (WHITE_LIST.includes(to.path)) {
        //进入if,表示当前访问的页面属于白名单页面
        return true;
    }
    //如果代码执行到这一行，就表示当前访问的页面不属于白名单页面
    //判断用户是否登录
    const token = localStorage.user_token;
    if (!token) {
        //进入if,这表示当前访问的页面需要先登录才能静茹，但是用户没有登录 
        return { path: '/login', replace: true };
    }
    //如果代码执行到这行。说明用户访问的是系统内部页面，并且登陆了
    /***
     * 1.调用状态机中公共的请求（发送请求获取权限数据）
     * 2.根据请求结果动态添加路由配置
     * 
     */
    const adminStore = useAdminStore();
    const permissions = await adminStore.getAdminInfoAsync();


    if (permissions && !isAdded) {
        console.log(routesDataFormat(permissions));
        
        routesDataFormat(permissions).forEach(item => {
            //MainView是父级路由的name值
            // console.log(item.component);
            //那到每个组件的路径
            router.addRoute('MainView', {
                path: item.path,
                //懒加载
                component: () => import('../views' + item.component + '.vue')
            })
        })

        isAdded = true;

        return {
            ...to,
            replace: true
        }

    }


    // routesDataFormat(permissions).forEach(item => {
    //     //MainView是父级路由的name值
    //     console.log(item.component);
    //     //那到每个组件的路径
    //     router.addRoute('MainView', {
    //         path: item.path,
    //         //懒加载
    //         component: () => import('../views' + item.component + '.vue')
    //     })
    // })




})











const routesDataFormat = (permissions: menuitem[]): menuitem[] => {
    // console.log(permissions);
    return permissions.reduce((prev: menuitem[], item: menuitem) => {
        //如果item.conponent存在，说明item要参与路由配置
        if (item.children) {
            //判断children中是否包含menu类型的数据
           const hasMenu=item.children.some(child=>child.type=='menu');
           if(hasMenu){
             //如果children中有menu类型，说明当前item是一级菜单，不参与路由配置
            return [
                ...prev,
                ...routesDataFormat(item.children)
            ]
           } 
            //如果children中全部都是button类型，说明当前item没有子菜单，要参与路由配置
          return[
            ...prev,
            item,
            ... routesDataFormat(item.children)
          ]

        }

        if (item.component) {
            return [
                ...prev,
                item
            ]
        }
   
        return prev;

    }, [])
}



export const toLogin=()=>{
    const adminStore=useAdminStore();
    adminStore.logout();
    router.replace({
        path:'/login'
    })
}






export let setupRouter = (app: App<Element>) => {
    app.use(router)
}

// export default router;
